package org.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.base.R;
import org.example.entity.Member;
import org.example.service.IMemberService;
import org.example.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@RestController
@Tag(name = "会员管理")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private IMemberService iMemberService;


    @RequestMapping("/findMemberAll")
    @Operation(summary = "查询所有会员")
    @Cacheable(cacheNames = "member", key = "'findMemberAll'")  //key和方法名对应 加''
    public R<List<Member>> findMemberAll() {
        return R.data(memberService.getMemberAll());
    }

    @GetMapping("/getMemberById/{id}")
    @Cacheable(cacheNames = "member", key = "#id")
    public Member getMemberById(@PathVariable Long id) {

        return iMemberService.getMemberById(id);
    }

    @PostMapping("/saveMember")
    @Cacheable(cacheNames = "member", key = "#member.name")
    public R saveMember(Member member) {
        boolean b = memberService.saveMember(member);

        if (b) {
            // 数据库有了想同的热门
            log.error("数据库有了相同的数据" + member);
            return R.fail("数据库有了相同的人名");
        }
        return R.success();
    }

    @PutMapping("/updateMember")
    public R updateMember(Member member) {
        boolean b = memberService.updateMember(member);
        if (b) {
            return R.success("更新成功");
        }
        return R.fail("更新失败");
    }

    @DeleteMapping("/deleteMemberById/{id}")
    public R deleteMemberById(@PathVariable Long id) {
        boolean b = memberService.removeMemberById(id);

        if (b) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @GetMapping("/getMemberByName/{name}")
    public Member getMemberByName(@PathVariable String name) {
        return memberService.getMemberByName(name);
    }

    @GetMapping("/getMemberPriceById/{id}")
    public BigDecimal getMemberPriceById(@PathVariable Long id) {
        return memberService.getMemberPriceById(id);
    }

    //充值
    @PutMapping("/recharge/{id}/{price}")
    public R recharge(@PathVariable Long id, @PathVariable BigDecimal price) {
        boolean b = memberService.recharge(id, price);
        if (b) {
            return R.success("充值成功");
        }
        return R.fail("充值失败");
    }

}
